﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WAF.Server.Ipc;
using WAF.Server;
using System.ServiceModel;

namespace PerformanceTests
{
    [ServiceBehavior( ConcurrencyMode = ConcurrencyMode.Multiple,
    InstanceContextMode = InstanceContextMode.Single)]    
    public class AppServerService : AppServerCore,  IAppServerIpcContract
    {
        Dictionary<Guid, IAppServerIpcCallbackContract> callbackChannels = new Dictionary<Guid,IAppServerIpcCallbackContract>();
        object callbackChannelsLock = new object();


        public AppServerService()
        {
            Init(ProcessResponse);
        }

        public void AddServer(Guid WebServerID)
        {
            IAppServerIpcCallbackContract callback = OperationContext.Current.GetCallbackChannel<IAppServerIpcCallbackContract>();
            if (callback == null)
                throw new InvalidOperationException("No callback channel available");
            lock (callbackChannelsLock)
            {
                callbackChannels.Add(WebServerID, callback);
            }
        }

        public void RemoveServer(Guid WebServerID)
        {
            lock (callbackChannelsLock)
            {
                callbackChannels.Remove(WebServerID);
            }
        }

        void ProcessResponse(ContentResponse response)
        {
            Guid serverID = response.Key.WebServerID;
            IAppServerIpcCallbackContract callback;
            lock (callbackChannelsLock)
            {
                callback = callbackChannels[serverID];
            }

            byte[] content = Guid.NewGuid().ToByteArray();
            response.Content = content;
            callback.AppServerResponse(response);
        }
    }
}
